import React, { useRef, useState } from 'react';
import _ from 'lodash';
import { history } from 'umi';
import CommonTable from '@/components/CommonTable';
import DebounceWrapper from '@/components/DebounceWrapper';
import PageActiveDialog from './components/resourceDialog';
import { Button, message, Popconfirm, Spin, Modal } from 'antd';
import {
  DeleteOutlined,
  EditOutlined,
  SendOutlined,
  SwitcherOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import {
  fetchDesignPageList,
  fetchDesignPageDetail,
  deletePageDesign,
  updatePageDesign,
} from '@/services/online/onlinePage';

const DebounceButton = DebounceWrapper(Button);

export default () => {
  const tableRef = useRef(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [deleteLoadingIds, setDeleteLoadingIds] = useState([]);
  const [sourceModalOptions, setSourceModalOptions] = useState({});
  const [sourceModalVisible, setSourceModalVisible] = useState(false);

  // 切换loading
  const toggleDeleteLoading = (id, status) => {
    setDeleteLoadingIds((list) => {
      const nextList = [...list];
      if (status) {
        nextList.push(id);
      } else {
        const index = _.indexOf(nextList, id);
        if (index > -1) {
          nextList.splice(index, 1);
        }
      }
      return nextList;
    });
  };

  // 激活/取消激活
  const handleStatusChange = (opts) => {
    const { pageId, status } = opts;
    if (status === 'unactivated') {
      setSourceModalOptions(opts);
      setSourceModalVisible(true);
    } else {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '确认取消该页面的菜单挂载?',
        onOk() {
          return new Promise((resolve, reject) => {
            updatePageDesign({ pageId, status: 'unactivated' })
              .then(() => {
                message.success('页面取消挂载成功');
                const { refresh } = tableRef.current;
                refresh && refresh();
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        },
      });
    }
  };

  // 查看/编辑
  const handleModify = ({ pageId, ...restOpts }) => {
    setDetailLoading(true);
    fetchDesignPageDetail({ pageId })
      .then((res) => {
        setDetailLoading(false);
        history.push({
          pathname: '/online/onlinePage/onlinePageDesign',
          state: { ...restOpts, pageContent: res, pageId },
        });
      })
      .catch(() => {
        setDetailLoading(false);
      });
  };

  return (
    <Spin spinning={detailLoading}>
      <CommonTable
        ref={tableRef}
        rowKey={'pageId'}
        indexRender
        header={{
          headerTitle: '设计页面列表',
          headerToolsRender: true,
          headerButtonList: [
            {
              key: 'design',
              type: 'primary',
              label: '前往设计',
              icon: <SendOutlined />,
            },
          ],
          headerButtonClick: async ({ key }) => {
            switch (key) {
              case 'design':
                history.push('/online/onlinePage/onlinePageDesign');
                break;
            }
          },
        }}
        request={async (params) => {
          const { records, total } = await fetchDesignPageList(params);
          return { data: records, count: total };
        }}
        columns={[
          {
            title: '页面名称',
            dataIndex: 'pageName',
            columnControl: { typeList: 'search' },
          },
          {
            title: '页面描述',
            dataIndex: 'pageDescription',
          },
          {
            title: '激活状态',
            dataIndex: 'status',
            columnControl: {
              typeList: 'filter',
              filterOptions: [
                { text: '激活', value: 'activated' },
                { text: '未激活', value: 'unactivated' },
              ],
            },
          },
          {
            title: '操作',
            dataIndex: 'pageId',
            width: 280,
            render: (pageId, data) => {
              const deleteLoading = _.includes(deleteLoadingIds, pageId);
              return (
                <>
                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<EditOutlined />}
                    loading={deleteLoading}
                    onClick={() => {
                      handleModify(data);
                    }}
                  >
                    查看/编辑
                  </DebounceButton>

                  <DebounceButton
                    type="link"
                    size="small"
                    icon={<SwitcherOutlined />}
                    loading={deleteLoading}
                    onClick={() => {
                      handleStatusChange(data);
                    }}
                  >
                    {data.status === 'unactivated' ? '激活' : '取消激活'}
                  </DebounceButton>

                  <Popconfirm
                    okText="确定"
                    cancelText="取消"
                    title={'确认删除该页面，删除后不可恢复'}
                    placement="topRight"
                    disabled={data.status !== 'unactivated'}
                    onConfirm={async () => {
                      toggleDeleteLoading(pageId, true);
                      try {
                        await deletePageDesign({ pageId });
                        const { refresh } = tableRef.current;
                        refresh && refresh();
                        message.success('页面删除成功');
                      } catch (e) {
                        console.log('删除失败');
                      }
                      toggleDeleteLoading(pageId, false);
                    }}
                  >
                    <DebounceButton
                      danger
                      type="link"
                      size="small"
                      icon={<DeleteOutlined />}
                      loading={deleteLoading}
                      disabled={data.status !== 'unactivated'}
                    >
                      删除
                    </DebounceButton>
                  </Popconfirm>
                </>
              );
            },
          },
        ]}
      />
      <PageActiveDialog
        visible={sourceModalVisible}
        options={sourceModalOptions}
        setDetailLoading={setDetailLoading}
        closeModal={() => {
          setSourceModalVisible(false);
          setSourceModalOptions({});
        }}
        updateList={() => {
          const { refresh } = tableRef.current;
          refresh && refresh();
        }}
      />
    </Spin>
  );
};
